﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zero.UControl.Base.Helper
{
    public static class LunarHelper
    {
        private static readonly ChineseLunisolarCalendar calendar = new ChineseLunisolarCalendar();
        private static readonly string[] ChineseDayNames =
        {
            "初一","初二","初三","初四","初五","初六","初七","初八","初九","初十",
            "十一","十二","十三","十四","十五","十六","十七","十八","十九","二十",
            "廿一","廿二","廿三","廿四","廿五","廿六","廿七","廿八","廿九","三十"
        };

        private static readonly string[] ChineseMonthNames =
        {
            "正月","二月","三月","四月","五月","六月","七月","八月","九月","十月","冬月","腊月"
        };

        private static readonly string[] SolarTerms =
        {
            "小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至",
            "小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至"
        };

        // 1900-2100的二十四节气数据（简化为近似计算）
        private static readonly int[] SolarTermInfo = new int[]
        {
            0,21208,42467,63836,85337,107014,128867,150921,173149,195551,218072,240693,
            263343,285989,308563,331033,353350,375494,397447,419210,440795,462224,483532,504758
        };

        /// <summary>
        /// 返回农历日期字符串（如 "初六" 或 "正月"）
        /// </summary>
        public static string GetLunarText(DateTime date)
        {
            int year = calendar.GetYear(date);
            int month = calendar.GetMonth(date);
            int day = calendar.GetDayOfMonth(date);

            int leapMonth = calendar.GetLeapMonth(year);
            if (leapMonth > 0 && month >= leapMonth)
                month--;

            string lunarMonth = ChineseMonthNames[(month - 1) % 12];
            string lunarDay = ChineseDayNames[(day - 1) % 30];

            if (day == 1)
                return lunarMonth; // 每月初一显示月份
            return lunarDay;
        }

        /// <summary>
        /// 计算节气（如果当天为节气则返回名称）
        /// </summary>
        public static string GetSolarTerm(DateTime date)
        {
            int year = date.Year;
            for (int i = 0; i < 24; i++)
            {
                DateTime term = GetSolarTermDate(year, i);
                if (term.Date == date.Date)
                    return SolarTerms[i];
            }
            return string.Empty;
        }

        private static DateTime GetSolarTermDate(int year, int index)
        {
            // 以1900年为基准计算近似节气时间
            DateTime baseDate = new DateTime(1900, 1, 6, 2, 5, 0);
            double minutes = 525948.76 * (year - 1900) + SolarTermInfo[index];
            return baseDate.AddMinutes(minutes * 60);
        }
    }
}
